package com.joyxuan.weixin;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.joyxuan.common.utile.LogUtil;
import com.joyxuan.common.utile.RequestUtil;

public class CommonController {
	private static RequestConfig requestLongConfig = RequestConfig.custom().setSocketTimeout(60000)
			.setConnectTimeout(60000).build();
	private static RequestConfig requestShortConfig = RequestConfig.custom().setSocketTimeout(6000)
			.setConnectTimeout(6000).build();
	private static final ObjectMapper mapper = new ObjectMapper();

	protected String post(String url, BasicNameValuePair[] params) {
		return post(url, Arrays.asList(params));
	}
	public String getTest() {
		return "xxxx";
	}
	/**
	 * 计算分页总页数 .
	 *
	 * @param totalCount
	 *            总记录数.
	 * @param numPerPage
	 *            每页记录数.
	 * @return totalPage 总页数.
	 */
	public static int countTotalPage(int totalCount, int numPerPage) {
		if (totalCount % numPerPage == 0) {
			// 刚好整除
			return totalCount / numPerPage;
		} else {
			// 不能整除则总页数为：商 + 1
			return totalCount / numPerPage + 1;
		}
	}

	protected int getPageNo(HttpServletRequest request) {
		String pageNoStr = StringUtils.isEmpty(request.getParameter("pages")) ? "1" : request.getParameter("pages");
		int pageNo = Integer.valueOf(pageNoStr);
		return pageNo;
	}

	protected int getPageSize(HttpServletRequest request) {
		String pageSizeStr = StringUtils.isEmpty(request.getParameter("pageSize")) ? "12"
				: request.getParameter("pageSize");
		int pageSize = Integer.valueOf(pageSizeStr);
		return pageSize;
	}

	/**
	 * post
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	protected String post(String url, List<BasicNameValuePair> params) {
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestShortConfig);
			if (CollectionUtils.isNotEmpty(params)) {
				UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");
				httpPost.setEntity(urlEncodedFormEntity);
			}

			CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
			try {
				HttpEntity httpEntity = closeableHttpResponse.getEntity();
				return EntityUtils.toString(httpEntity, "UTF-8");
			} catch (Exception e) {
				LogUtil.debug("请求失败: " + url + " 异常: " + e.getMessage());
			} finally {
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			HttpClientUtils.closeQuietly(closeableHttpClient);
		}
		HttpClientUtils.closeQuietly(closeableHttpClient);

		return null;
	}

	protected void outputJsonData(Object obj, HttpServletResponse response) {
		try {
			String jsonString = "";
			if ((obj instanceof String)) {
				jsonString = (String) obj;
			} else if ((obj instanceof Map)) {
				Map<Object, Object> map = (Map) obj;
				for (Map.Entry<Object, Object> entry : map.entrySet()) {
					if (entry.getValue() == null) {
						entry.setValue("");
					}
				}
				jsonString = mapper.writeValueAsString(map);
			} else {
				jsonString = mapper.writeValueAsString(obj);
			}
			doOutput("text/json;charset=utf-8", jsonString, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected String getSystemPath() {
		return RequestUtil.getRequest().getScheme() + "://" + RequestUtil.getRequest().getServerName()
				+ RequestUtil.getRequest().getContextPath() + "/";
	}

	protected final void doOutput(String contentType, String value, HttpServletResponse response) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType(contentType);
			response.setHeader("progma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0L);
			response.getWriter().print(value);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
